<template>
    <!-- 搜素 -->
    <div class="search-box">
        <div class="flex">
            <div>
                <el-icon>
                    <Search />
                </el-icon><span>筛选搜索</span>
            </div>
            <div>
                <el-button @click="resetFn">重置</el-button>
                <el-button type="primary" @click="searchFn">查询搜索</el-button>
            </div>
        </div>
        <div style="padding-top: 20px">
            <el-form ref="formRef">
                <el-form-item label="输入搜索:" prop="keyword" label-width="120px">
                    <el-input style="width: 220px" size="large" placeholder="商品名称" v-model="keyword"></el-input>
                </el-form-item>
                <el-form-item label="商品货号:" prop="productSn" label-width="120px">
                    <el-input style="width: 220px" size="large" placeholder="商品货号" v-model="productSn"></el-input>
                </el-form-item>
                <el-form-item label="商品分类:" prop="productCategoryId" label-width="120px">
                    <el-cascader :options="proCategories" :props="props1" clearable />
                </el-form-item>
                <el-form-item label="商品品牌:" prop="brandId" label-width="120px">
                    <el-select v-model="brandId" class="m-2" placeholder="请选择品牌" size="large">
                        <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="上架状态:" prop="publishStatus" label-width="120px">
                    <el-select v-model="publishStatus" class="m-2" placeholder="全部" size="large">
                        <el-option label="上架" :value="1" />
                        <el-option label="下架" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="审核状态:" prop="verifyStatus" label-width="120px">
                    <el-select v-model="verifyStatus" class="m-2" placeholder="全部" size="large">
                        <el-option label="审核通过" :value="1" />
                        <el-option label="未审核" :value="0" />
                    </el-select>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <!-- 添加 -->
    <div class="add-box">
        <div class="data-list">
            <el-icon>
                <Tickets />
            </el-icon>
            <span>数据列表</span>
        </div>
        <el-button type="default" @click="router.push('/pms/addProduct')">添加</el-button>
    </div>
    <el-table :data="productsList" border fit @selection-change="handleSelectionChange" ref="multipleTableRef">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="编号"></el-table-column>
        <el-table-column prop="pic" label="商品图片" width="160">
            <template #default="scope">
                <el-image style="width: 100px; height: 100px" :src="scope.row.pic" fit="fill">
                    <template #error>
                        <div class="image-slot">
                            <el-icon>
                                <icon-picture />
                            </el-icon>
                        </div>
                    </template>
                </el-image>
            </template>
        </el-table-column>
        <el-table-column label="商品名称" width="140">
            <template #default="scope">
                <div>{{ scope.row.name }}</div>
                <div>品牌：{{ scope.row.brandName }}</div>
            </template>
        </el-table-column>
        <el-table-column label="价格/货号" width="160">
            <template #default="scope">
                <div>价格：{{ scope.row.price }}</div>
                <div>货号：{{ scope.row.serviceIds }}</div>
            </template>
        </el-table-column>
        <el-table-column label="标签" width="140">
            <template #default="scope">
                <div>
                    上架：<el-switch v-model="scope.row.publishStatus" :active-value="1" :inactive-value="0"
                        @change="updateProductPublishStatus(scope.row.id, scope.row.publishStatus)">
                    </el-switch>
                </div>
                <div>
                    新品：<el-switch v-model="scope.row.newStatus" :active-value="1" :inactive-value="0"
                        @change="updateProductNewStatus(scope.row.id, scope.row.newStatus)">
                    </el-switch>
                </div>
                <div>
                    推荐：<el-switch v-model="scope.row.recommandStatus" :active-value="1" :inactive-value="0"
                        @change="updateProductRecommendStatus(scope.row.id, scope.row.recommandStatus)">
                    </el-switch>
                </div>
            </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序"></el-table-column>
        <el-table-column prop="navStatus" label="SKU库存" width="100">
            <template #default="scope">
                <el-button type="primary" :icon="Edit" circle size="large" @click="editSKUFn(scope.row.id)" />
            </template>
        </el-table-column>
        <el-table-column prop="sale" label="销量">
        </el-table-column>

        <el-table-column label="审核状态" width="120">
            <template #default="scope">
                <span>{{ scope.row.verifyStatus === 0 ? '未审核' : '审核通过' }}</span>
                <el-button type="primary" link>审核详情</el-button>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="140" fixed="right">
            <template #default="scope">
                <el-button type="default" size="small" @click="editFn(scope.row.id)">编辑</el-button>
                <el-button type="danger" size="small" @click="delFn(scope.row.id)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 页尾 -->
    <div class="bottom">
        <!-- 批量操作 -->
        <div>
            <el-select class="m-2" placeholder="批量操作" size="large" @change="handelChangeFn" v-model="selectID">
                <el-option v-for="item in operations" :key="item.id" :label="item.text" :value="item.id" />
            </el-select>
            <el-button type="primary" @click="sureOperate">确定</el-button>
        </div>
        <!-- 分页 -->
        <ElConfigProvider :locale="zhCn">
            <el-pagination v-model:currentPage="pageNum" v-model:page-size="pageSize" background
                layout="total, sizes, prev, pager, next ,jumper" :total="total" @size-change="pageSizeChange"
                @current-change="pageNumChange" :page-sizes="[5, 10, 15]" />
        </ElConfigProvider>
    </div>
    <!-- 编辑货品信息 -->
    <editSKU :show="showEditSKU" @hide="handelHideFn" :data="editSKUID"></editSKU>
</template>
<script setup lang='ts'>
import { Tickets, Search } from '@element-plus/icons-vue';
import { pro } from '@/api'
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { ElConfigProvider, ElMessage, ElMessageBox, ElTable, FormInstance } from "element-plus";
import { reactive, ref, toRefs } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { Picture as IconPicture, Edit } from '@element-plus/icons-vue'
import editSKU from './components/editSKU.vue'
const router = useRouter()
interface Istate {
    productsList: IProductListModel[],
    total: number,
    brandList: IProBrandsModel[],
    proCategories: IProductCategoryWithChildrenModel[]
}

// 请求返回的数据
const state = reactive<Istate>({
    productsList: [],
    total: 0,
    brandList: [],
    proCategories: []
})
// 请求参数
const params = reactive<IGetProductListParams>({
    pageNum: 1,
    pageSize: 5,
    keyword: '',
    brandId: '',
    productCategoryId: '',
    productSn: '',
    publishStatus: '',
    verifyStatus: ''
})
// 批量操作
const operations = reactive([
    {
        id: 1,
        status: 1,
        text: '商品上架'
    },
    {
        id: 2,
        status: 0,
        text: '商品下架'
    },
    {
        id: 3,
        status: 1,
        text: '设为推荐'
    },
    {
        id: 4,
        status: 0,
        text: '取消推荐'
    },
    {
        id: 5,
        status: 1,
        text: '设为新品'
    },
    {
        id: 6,
        status: 0,
        text: '取消新品'
    },
    {
        id: 7,
        status: 1,
        text: '转移到分类'
    },
    {
        id: 8,
        status: 1,
        text: '移入回收站'
    }
])
const status = ref<number | string>('')
const ids = ref<number[]>([])
const selectID = ref<number | string>('')
const formRef = ref<FormInstance>()
// dialog
const showEditSKU = ref(false)
const editSKUID = ref(0)

let { productsList, total, brandList, proCategories } = toRefs(state);
let { pageNum, pageSize, keyword, productSn, brandId, productCategoryId, publishStatus, verifyStatus } = toRefs(params);

// 封装商品列表请求
const getProductsList = () => {
    pro.getProductListApi(params).then(res => {
        if (res.code === 200) {
            state.productsList = res.data.list;
            state.total = res.data.total;
        }
    })
}
Promise.all([pro.getProductListApi(params), pro.getProBrandsApi({ pageNum: 1, pageSize: 100 }), pro.getProductCategoryWithChildrenApi()]).then(([products, brands, attrs]) => {
    if (products.code === 200 && brands.code === 200 && attrs.code === 200) {
        state.productsList = products.data.list;
        state.total = products.data.total;
        state.brandList = brands.data.list;
        state.proCategories = attrs.data
    }
}).catch(err => {
    console.log(err);
})
// 级联 商品分类
const props1 = {
    checkStrictly: true,
    value: 'id',
    label: 'name',
    children: 'children'
}
// 分页
const pageSizeChange = () => {
    getProductsList();
}
const pageNumChange = () => {
    getProductsList();
}
// 搜索
const searchFn = () => {
    getProductsList();
}
// 重置
const resetFn = () => {
    // formRef.value?.resetFields()
    params.keyword = '';
    params.brandId = '';
    params.productCategoryId = '';
    params.productSn = '';
    params.publishStatus = '';
    params.verifyStatus = '';
    getProductsList();
}

// 批量操作select
const handelChangeFn = (id: number) => {
    let idx = operations.findIndex(item => item.id === id)
    status.value = operations[idx].status
}
// 批量操作
// 封装
const updateProductPublishStatus = (ids: number[], publishStatus: number) => {
    pro.updateProductPublishStatusApi({ ids, publishStatus }).then(res => {
        ElMessage({
            message: res.message,
            type: res.code === 200 ? 'success' : 'error'
        })
        if (res.code === 200) {
            getProductsList();
        }
    });
}
const updateProductNewStatus = (ids: number[], newStatus: number) => {
    pro.updateProductNewStatusApi({ ids, newStatus }).then(res => {
        ElMessage({
            message: res.message,
            type: res.code === 200 ? 'success' : 'error'
        })
        if (res.code === 200) {
            getProductsList();
        }
    });
}
const updateProductRecommendStatus = (ids: number[], recommendStatus: number) => {
    pro.updateProductRecommendStatusApi({ ids, recommendStatus }).then(res => {
        ElMessage({
            message: res.message,
            type: res.code === 200 ? 'success' : 'error'
        })
        if (res.code === 200) {
            getProductsList();
        }
    });
}
const sureOperate = () => {
    ElMessageBox.confirm(
        '是否要进行该批量操作?',
        '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }
    ).then(() => {
        if (selectID.value === 1 || selectID.value === 2) {
            updateProductPublishStatus(ids.value, status.value as number)

        } else if (selectID.value === 3 || selectID.value === 4) {
            updateProductRecommendStatus(ids.value, status.value as number)

        } else if (selectID.value === 5 || selectID.value === 6) {
            updateProductNewStatus(ids.value, status.value as number)

        } else if (selectID.value === 8) {
            pro.updateProductDeleteStatusApi({ ids: ids.value, deleteStatus: status.value as number }).then(res => {
                ElMessage({
                    message: res.message,
                    type: res.code === 200 ? 'success' : 'error'
                })
                if (res.code === 200) {
                    getProductsList();
                }
            })
        }
    })

}
// 表格全选、单选
const handleSelectionChange = (data: any[]) => {
    ids.value = data.map(item => item.id)
}
// SKU库存
const handelHideFn = () => {
    showEditSKU.value = false
    editSKUID.value = 0
}
const editSKUFn = (id: number) => {
    showEditSKU.value = true
    editSKUID.value = id
}
// 编辑
const editFn = (id: number) => {
    router.push(`/pms/addProduct?id=${id}`)
}
// 删除
const delFn = (id: number) => { }
</script>
<style lang="less" scoped>
.search-box {
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 10px;
    margin: 20px 0;

    .flex {
        display: flex;
        justify-content: space-between;
    }

    .el-form {
        width: 100%;
        display: flex;
        flex-wrap: wrap;

        .el-form-item {
            width: 50%;


        }
    }
}

.add-box {
    padding: 15px;
    display: flex;
    justify-content: space-between;
    border: 1px solid #ebeef5;
    border-radius: 5px;
    align-items: center;
    margin-bottom: 20px;

    .data-list {
        display: flex;
        align-items: center;
    }
}

.bottom {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20px;

    .el-button {
        margin-left: 20px;
    }
}

.image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
}

.image-slot .el-icon {
    font-size: 30px;
}
</style>